package com.summer.common.lib.context;

import com.summer.common.lib.context.impl.JNDIInitialize;
import com.summer.common.lib.context.impl.JNDIInstantiate;

import javax.servlet.ServletContext;

public class WebContext {

    public static final String CONTEXT_NAME = WebContext.class.getName();

    /**
     * ServletContext 上下文, 存入当前的 ClassLoader 缓存
     */
    private static ServletContext servletContext;

    private static JNDIInstantiate jndiInstantiate;

    /**
     * ServletContext 的类加载器
     */
    private ClassLoader classLoader;

    public WebContext(ServletContext servletContext) {
        // 获取当前Servlet 类加载器
        this.classLoader = servletContext.getClassLoader();
        this.init(servletContext);
    }

    public WebContext(ServletContext servletContext, ClassLoader classLoader) {
        this.classLoader = classLoader;
        init(servletContext);
    }

    private void init(ServletContext servletContext) {
        WebContext.servletContext = servletContext;
        // 将当前类存入ServletContext
        servletContext.setAttribute(CONTEXT_NAME, this);
        // 实例化组件
        jndiInstantiate = new JNDIInstantiate("/", this.classLoader);
        // 初始化组件
        new JNDIInitialize(
                jndiInstantiate
        );
    }

    /**
     * 通过名称进行依赖查找
     *
     * @param name
     * @param <C>
     * @return
     */
    public static <C> C getComponent(String name) {
        return (C) jndiInstantiate.getAllComponents().get(name);
    }

    /**
     * 获取ServletContext
     *
     * @return
     */
    public static ServletContext getServletContext() {
        return servletContext;
    }

    public static Instantiate getInstantiate() {
        return jndiInstantiate;
    }
}
